package com.ydj.app.config.resolver;

import com.ydj.app.WebConst;
import com.ydj.app.entity.WebUser;
import com.ydj.app.entity.dao.WebUserDao;
import com.ydj.app.protocol.redis.RdsWebLoginInfo;
import com.ydj.framework.exception.VerifyTokenException;
import com.ydj.framework.resolver.BaseArgumentResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * CMS参数转换器
 */
@Configuration
public class WebArgumentResolver extends BaseArgumentResolver<RdsWebLoginInfo> {
    @Autowired
    private WebUserDao webUserDao;

    @Autowired
    private WebConst mpConst;

    @Override
    public String prePath() {
        return mpConst.getBaseUrl() + "/";
    }

    @Override
    protected void createArgFormat(List<ArgFormat> list) {
        list.add(new ArgFormat("webUserId", Long.class));
        list.add(new ArgFormat("webUser", WebUser.class));
    }

    @Override
    protected Object doResolveArgument(String parameterName, RdsWebLoginInfo info) throws VerifyTokenException {
        switch (parameterName) {
            case "webUserId":
                return getUserId(info);
            case "webUser":
               return getUser(info);
            default:
                break;
        }
        return null;
    }

    private Long getUserId(RdsWebLoginInfo info) throws VerifyTokenException {
        Long userId = info.getWebUserId();
        if (userId == null) {
            throw new VerifyTokenException();
        }
        return userId;
    }

    private WebUser getUser(RdsWebLoginInfo info) throws VerifyTokenException {
        Long userId = getUserId(info);
        WebUser user = webUserDao.getById(userId);
        if (user == null) {
            throw new VerifyTokenException();
        }
        return user;
    }
}